package com.asen.libcommon.eventBus

import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.OnLifecycleEvent
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * @date   : 2021/1/14
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : EventBus生命周期监听回调，拓展函数无需在基类封装使基类代码脓肿
 */
open class EventBusLifecycleObserver<T>(open val callBack: (T) -> Unit) : LifecycleObserver {

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private fun onCreate() {
        EventBusUtil.register(this)
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private fun onDestroy() {
        EventBusUtil.unregister(this)
    }

}

/**
 * 根据已经封装的 EventBusHelp 开放出来使用
 */
class EventBusHelpLifecycleObserver(callBack: (EventBusEntity) -> Unit) :
    EventBusLifecycleObserver<EventBusEntity>(callBack) {
    /**
     * 获取接收EventBus数据
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    open fun onEvent(event: EventBusEntity) {
        callBack.invoke(event)
    }
}